package com.szh.taobaounion.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.Views.TBNestedSceolView;
import com.szh.taobaounion.Presenter.ICategoryPagerPresenter;
import com.szh.taobaounion.R;
import com.szh.taobaounion.base.BaseFragment;
import com.szh.taobaounion.model.domain.CateGories;
import com.szh.taobaounion.model.domain.HomePagerContent;
import com.szh.taobaounion.model.domain.IBaseInfo;
import com.szh.taobaounion.ui.adapter.LinearItemContentAdapter;
import com.szh.taobaounion.ui.adapter.LooperPagerAdapter;
import com.szh.taobaounion.ui.custom.AutoLoopViewPager;
import com.szh.taobaounion.utils.Constants;
import com.szh.taobaounion.utils.LogUtils;
import com.szh.taobaounion.utils.PresenterManager;
import com.szh.taobaounion.utils.SizeUtils;
import com.szh.taobaounion.utils.TicketUtil;
import com.szh.taobaounion.utils.ToastUtil;
import com.szh.taobaounion.view.ICategoryPagerCallBack;

import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePagerFragment extends BaseFragment implements ICategoryPagerCallBack, LinearItemContentAdapter.onItemClickListener, LooperPagerAdapter.onLooperPagerItemClickListener {

    private ICategoryPagerPresenter mCatregoryPagerPresent;
    private int mMaterialId;
    private LinearItemContentAdapter mHomePagerContentAdapter;
    private LooperPagerAdapter mLooperPagerAdapter;

    public static HomePagerFragment newInstance(CateGories.DataBean category) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, category.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID, category.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;
    @BindView(R.id.looper_pager)
    public AutoLoopViewPager looperPager;
    @BindView(R.id.homer_pager_title)
    public TextView currentCategoryTitle;

    @BindView(R.id.looper_point_container)
    public LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout twinklingRefreshLayout;

    @BindView(R.id.home_pager_parent)
    public LinearLayout homePagerParent;
    @BindView(R.id.home_pager_header_container)
    public LinearLayout homePagerHeaderContainer;
    @BindView(R.id.home_pager_nested_scroll)
    public TBNestedSceolView homePagerNestedScroll;
    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }



    @Override
    protected void initView(View rootView) {
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        //创建适配器
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = 5;
                outRect.bottom = 5;
            }
        });
        mHomePagerContentAdapter = new LinearItemContentAdapter();
        //设置适配器
        mContentList.setAdapter(mHomePagerContentAdapter);

        //创建轮播图适配器
        mLooperPagerAdapter = new LooperPagerAdapter();
        //设置轮播图适配器
        looperPager.setAdapter(mLooperPagerAdapter);
        //设置twinklingRefreshLayout 相关内容
        twinklingRefreshLayout.setEnableRefresh(false);
        twinklingRefreshLayout.setEnableLoadmore(true);
        //twinklingRefreshLayout.setBottomView();
    }
    @Override
    public void onResume() {
        LogUtils.d(this,"onResume");
        super.onResume();
        //可见时调用
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        //不可见时调用
        looperPager.stopLoop();
        LogUtils.d(this,"onPause");
    }
    @Override
    protected void initListener() {
        mHomePagerContentAdapter.setonItemClickListener(this);
        mLooperPagerAdapter.setonItemClickListener(this);
        homePagerParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (homePagerHeaderContainer == null) {
                    return;
                }
                int headerHeight = homePagerHeaderContainer.getMeasuredHeight();
               // LogUtils.d(HomePagerFragment.this,"headerHeight"+headerHeight);
                homePagerNestedScroll.setHeaderHeight(headerHeight);
                int height = homePagerParent.getMeasuredHeight();
                //LogUtils.d(HomePagerFragment.this,"height---->"+height);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
                layoutParams.height=height;
                mContentList.setLayoutParams(layoutParams);
                if (height != 0) {
                    homePagerParent.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        looperPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mLooperPagerAdapter.getDataSize() == 0) {
                    return;
                }
                //切换指示器
                int targetPosition = position % mLooperPagerAdapter.getDataSize();
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //下拉刷新
        twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                LogUtils.d(HomePagerFragment.this, "触发了lodermore");
                //TODO:加载更多内容
                if (mCatregoryPagerPresent != null) {
                    mCatregoryPagerPresent.lodeMore(mMaterialId);
                }
            }
        });
    }

    /**
     * 切换指示器
     *
     * @param targetPosition
     */
    private void updateLooperIndicator(int targetPosition) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View point = looperPointContainer.getChildAt(i);
            if (i == targetPosition) {
                point.setBackgroundResource(R.drawable.shape_indacator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indacator_point_normal);
            }
        }


    }

    @Override
    protected void initPresenter() {
        mCatregoryPagerPresent = PresenterManager.getInstance().getmCatregoryPagerPresent();
        mCatregoryPagerPresent.registerViewCallBack(this);
    }

    @Override
    protected void LoadData() {
        Bundle arguments = getArguments();
        String title = arguments.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId = arguments.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        LogUtils.d(this, "title+" + title);
        LogUtils.d(this, "materialId+" + mMaterialId);
        //TODO:加载数据
        if (mCatregoryPagerPresent != null) {
            mCatregoryPagerPresent.getcontentByCategoryId(mMaterialId);
        }
        if (currentCategoryTitle != null) {
            currentCategoryTitle.setText(title);
        }
    }

    @Override
    public int GetCategoryId() {
        return mMaterialId;
    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> contents) {
        // 数据列表加载
        //TODO:更新Ui
        mHomePagerContentAdapter.setmData(contents);
        setUpState(State.SUCCESS);
    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        setUpState(State.Empty);
    }


    @Override
    public void onLoderMoreError() {
        if (twinklingRefreshLayout != null) {
            twinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.ShowToast("网络错误请重试....");
    }

    @Override
    public void onLoderMoreEmpty() {
        if (twinklingRefreshLayout != null) {
            twinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.ShowToast("没有更多的商品..");
    }

    @Override
    public void onLoderMoreLoaded(List<HomePagerContent.DataBean> contents) {
        //添加到适配器数据底部
        mHomePagerContentAdapter.addData(contents);
        if (twinklingRefreshLayout != null) {
            twinklingRefreshLayout.finishLoadmore();
        }
        ToastUtil.ShowToast("加载了" + contents.size() + "条数据");
    }

    @Override
    public void onLoderLooperListLoaded(List<HomePagerContent.DataBean> contents) {
        //LogUtils.d(this, "looper----->" + contents.size());
        mLooperPagerAdapter.setData(contents);
        //设置到中间点
        int dx = (Integer.MAX_VALUE / 2) % contents.size();
        int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;
        //LogUtils.d(this, "iv url---->" + contents.get(0).getPict_url());
        looperPager.setCurrentItem(targetCenterPosition);
        looperPointContainer.removeAllViews();
        //添加小圆点
        for (int i = 0; i < contents.size(); i++) {
            View point = new View(getContext());
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
            layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);
            point.setLayoutParams(layoutParams);
            if (i == 0) {
                point.setBackgroundResource(R.drawable.shape_indacator_point_selected);
            } else {
                point.setBackgroundResource(R.drawable.shape_indacator_point_normal);
            }
            looperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if (mCatregoryPagerPresent != null) {
            mCatregoryPagerPresent.unregisterViewCallBack(this);
        }
    }


    @Override
    public void onItemClick(IBaseInfo item) {
        //列表内容被点击
       // LogUtils.d(this,"item click--->"+item.getTitle());
        handleItemClick(item);
    }

    private void handleItemClick(IBaseInfo item) {

        TicketUtil.toTicketPage(getContext(),item);

    }

    @Override
    public void onLooperItemClick(IBaseInfo item) {
        //LogUtils.d(this,"item loop click--->"+item.getTitle());
        handleItemClick(item);
    }
}
